package com.ziroom.zifamily.zfms.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * WebApp工具类
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author cuiyh9
 * @version 1.0
 * @Date Created in 2018年11月24日 17:35
 * @since 1.0
 */
public class WebAppUtils {

    private static final String CONS_UNKNOWN = "unKnown";

    private static final String HEADER_REAL_IP = "X-Real-IP";

    private static final String HEADER_FORWARDED_FOR = "X-Forwarded-For";

    private static final String HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";

    private static final String HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";

    private static final String HEADER_HTTP_CLIENT_IP = "HTTP_CLIENT_IP";

    private static final String HEADER_HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR";


    private WebAppUtils() {

    }

    public static String getRemoteIp() {

        HttpServletRequest request = ((ServletRequestAttributes)      RequestContextHolder.getRequestAttributes()).getRequest();
        String xIp = request.getHeader(HEADER_REAL_IP);
        String xFor = request.getHeader(HEADER_FORWARDED_FOR);
        if(StringUtils.isNotEmpty(xFor) && !CONS_UNKNOWN.equalsIgnoreCase(xFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xFor.indexOf(",");
            if(index != -1){
                return xFor.substring(0,index);
            }else{
                return xFor;
            }
        }
        xFor = xIp;
        if(StringUtils.isNotEmpty(xFor) && !CONS_UNKNOWN.equalsIgnoreCase(xFor)){
            return xFor;
        }
        if (StringUtils.isBlank(xFor) || CONS_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader(HEADER_PROXY_CLIENT_IP);
        }
        if (StringUtils.isBlank(xFor) || CONS_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader(HEADER_WL_PROXY_CLIENT_IP);
        }
        if (StringUtils.isBlank(xFor) || CONS_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader(HEADER_HTTP_CLIENT_IP);
        }
        if (StringUtils.isBlank(xFor) || CONS_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader(HEADER_HTTP_X_FORWARDED_FOR);
        }
        if (StringUtils.isBlank(xFor) || CONS_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getRemoteAddr();
        }
        return xFor;
    }
}
